<style>
	@keyframes siz {
		0% {
			color: #fff;
		}

		50% {
			color: blue;
		}

		100% {
			color: green;
		}

	}

	.langya6 {
		animation: siz 1s linear infinite;
	}
</style>
<template>
	<view class="langya0">
		<view class="langya1">
			<image src="@/static/images/ly.png" mode="widthFix"></image>
		</view>
		<view class="langya5" v-if="showBtn">
			{{ list[0].deviceId}}连接成功
		</view>
		<view class="langya5 langya6" v-if="!showBtn">
			蓝牙连接中,请稍等
		</view>
		<view class="langya2" v-if="showBtn">
			<view class="langya3" @click="openBluetoothAdapterPay('openSelf')">激活机身</view>

			<view class="langya4" @click="openWeiXinAlipay">弹出刷头</view>
			<!-- <view class="langya4" @click="openWeiXinAlipay">弹出刷头</view> -->
		</view>

	</view>

</template>

<script>
	var that;
	export default {
		data() {
			return {
				getUserInfo: {},
				// getUserInfoDataToken: false,
				showBtn: false,
				bleAdapter: {
					available: false
				},
				bleConnection: false,
				list: [],
				serviceId: "",
				deviceId: "",
				timer25: null,
				unids: "",
				timer: null,

			}
		},
		onLoad() {
			that = this;

		},
		onShow() {
			that.weixinAuther();
			that.timer = setInterval(() => {
				that.writeBLECharacteristicValue2('PZSS')
			}, 26000)
		},
		onHide() {
			console.log("=====重复退出=>")
			clearInterval(that.timer)
			that.stopBluetoothDevicesDiscovery();
		},
		methods: {



			onAdapter() {
				console.log('启动-适配器-监听器');
				uni.onBluetoothAdapterStateChange(function(e) {
					console.log('监听到适配器的状态 =》', JSON.stringify(e))
					that.bleAdapter = e

				})
			},
			onConnection() {
				console.log('启动-连接状态-监听器');
				uni.onBLEConnectionStateChange(function(e) {
					// that.bleConnection = e.connected
					console.log('监听到蓝牙设备连接的状态 =》', JSON.stringify(e))
					that.startBluetoothDevicesDiscovery()
				})
			},
			initBLEAdP() {

				console.log('蓝牙适配器初始化成功！');

				uni.openBluetoothAdapter({
					success: (res) => { //已打开
						uni.getBluetoothAdapterState({
							success: (res1) => {
								that.bleAdapter = {
									available: true
								};
								that.startBluetoothDevicesDiscovery()
							},
							fail(error) {
								uni.showToast({
									icon: 'none',
									duration: 2000,
									title: '查看手机蓝牙是否打开1'
								});
							}
						});

					},
					fail: err => {
						//未打开 
						uni.showToast({
							icon: 'none',
							duration: 20000,
							title: '请打开手机蓝牙'
						});
					}
				})

			},
			//开始搜索蓝牙设备  
			startBluetoothDevicesDiscovery() {
				if (!this.bleAdapter.available) {
					this.initBLEAdP();
					return
				}
				uni.startBluetoothDevicesDiscovery({
					success(res) {
						console.log("正在搜索蓝牙设备...,启动现设备监听", res)

						that.onBluetoothDeviceFound();

					},
					fail(e) {
						console.log('搜索蓝牙失败，错误码：' + (e.errCode || e.errMsg));
					}
				})
			},
			//监听发现蓝牙设备  
			onBluetoothDeviceFound() {

				uni.onBluetoothDeviceFound(devices => {
					// console.log("启动发现设备监听", devices)

					this.getBluetoothDevices();

				});

			},
			//获取在蓝牙模块生效期间所有已发现的蓝牙设备。包括已经和本机处于连接状态的设备  
			getBluetoothDevices() {
				uni.getBluetoothDevices({
					success: res => {

						// #ifdef MP-ALIPAY
						var arr = res.devices;
						for (let i = 0, len = arr.length; i < len; i++) {
							if (that.list.indexOf(arr[i].deviceId) == -1) {
								console.log('----this.list------', arr[i])
								if (arr[i].name != null && arr[i].name.slice(0, 4) === 'WMD8') {
									that.connectToBLE(arr[i].deviceId)

									that.list.push({
										name: arr[i].name,
										deviceId: arr[i].deviceId
									})
									uni.setStorageSync("uuids", arr[i].name.slice(4))
                                     return
								}

							}
						}
						// #endif


						// #ifdef MP-WEIXIN 
						var alldevices = res.devices.filter(function(obj) {
							return obj.name.indexOf('WMD8') != -1 //此处是过滤自己想要连接的蓝牙设备
						})
						that.list = alldevices;
						that.connectToBLE(alldevices[0].deviceId)

						uni.setStorageSync("uuids", that.list[0].name.slice(4))
						// #endif





					},
					fail: e => {
						console.log('获取蓝牙设备错误，错误码：' + e.errCode);

					}
				});
			},
			stopBluetoothDevicesDiscovery(types) {
				uni.stopBluetoothDevicesDiscovery({
					success: e => {
						that.getBLEDeviceServices()
						console.log('停止搜索蓝牙设备:' + e.errMsg);
					},
					fail: e => {
						console.log('停止搜索蓝牙设备失败，错误码：' + e.errCode);

					}
				});
			},
			connectToBLE(deviceId) {
				that.deviceId = deviceId;
				console.log('device==>', deviceId)
				uni.createBLEConnection({
					deviceId,
					success(e) {
						that.stopBluetoothDevicesDiscovery();

						console.log('----------------开始获取蓝牙服务-------------->')
					}
				})

				// uni.stopBluetoothDevicesDiscovery();

			},
			//获取蓝牙的所有服务
			getBLEDeviceServices() {
				setTimeout(() => {
					uni.getBLEDeviceServices({
						// 这里的 deviceId 需要已经通过 createBLEConnection 与对应设备建立链接
						deviceId: that.deviceId,
						success: (res) => {
							console.log('获取到蓝牙所有的服务:', res)
							res.services.forEach((item) => {
								// #ifdef MP-WEIXIN
								if (item.uuid.indexOf("FFE0") != -1) {
									that.serviceId = item.uuid;
									console.log("1800特征值", that.serviceId)
									//获取特征
									that.getBLEDeviceCharacteristics()
								}
								// #endif
								// #ifdef MP-ALIPAY
								if (item.uuid.indexOf("ffe0") != -1) {
									// that.characteristicId = item.characteristicId
									that.serviceId = item.uuid;
									that.getBLEDeviceCharacteristics()
									//console.log('characteristicId:', item.uuid)
									//利用传参的形势传给下面的notify，这里的uuid如果都需要用到，就不用做判断了，建议使用setTimeout进行间隔性的调用此方法
									// that.notifyBLECharacteristicValueChange(item
									// 	.characteristicId)
								}
								// #endif
							})
						}
					})
				}, 1000)
			},
			//获取蓝牙特征
			getBLEDeviceCharacteristics() {

				console.log("进入特征");
				setTimeout(() => {
					uni.getBLEDeviceCharacteristics({
						// 这里的 deviceId 需要已经通过 createBLEConnection 与对应设备建立链接
						deviceId: that.deviceId,
						// 这里的 serviceId 需要在 getBLEDeviceServices 接口中获取
						serviceId: that.serviceId,
						success: (res) => {
							console.log('特征getBLEDeviceCharacteristics', res)
							that.characteristics = res.characteristics
							console.log('特征数组', that.characteristics)
							// "0000FFE1-0000-1000-8000-00805F9B34FB"
							res.characteristics.forEach((item) => {
								// #ifdef MP-WEIXIN
								if (item.uuid.indexOf("FFE1") != -1) {
									that.characteristicId = item.uuid;
									that.showBtn = true
									//console.log('characteristicId:', item.uuid)
									//利用传参的形势传给下面的notify，这里的uuid如果都需要用到，就不用做判断了，建议使用setTimeout进行间隔性的调用此方法
									// that.notifyBLECharacteristicValueChange(item.uuid)
								}
								// #endif
								// #ifdef MP-ALIPAY
								if (item.characteristicId.indexOf("ffe1") != -1 || item
									.characteristicId.indexOf("FFE1") != -1) {
									that.characteristicId = item.characteristicId;
									that.showBtn = true
									// that.notifyBLECharacteristicValueChange(item
									// 	.characteristicId)
									//console.log('characteristicId:', item.uuid)
									//利用传参的形势传给下面的notify，这里的uuid如果都需要用到，就不用做判断了，建议使用setTimeout进行间隔性的调用此方法
									// that.notifyBLECharacteristicValueChange(item.uuid)
								}
								// #endif
							})
						},
						fail: (res) => {
							console.log(res)
						}
					})
				}, 1000)
			},
			// 开盒流程
			openWeiXinAlipay() {
				// #ifdef MP-WEIXIN
				that.openBluetoothAdapterPay('open');
				// #endif
				// #ifdef MP-ALIPAY
				that.createOrderAlipay()
				// #endif
			},
			//支付宝创建订单
			createOrderAlipay() {
				uni.request({
					url: 'https://ys.shningmi.com/api/alipay/order',
					data: {
						guid: "guid", //暂时商品参数唯一标识
						qty: 1, //数量
						latitude: "",
						longitude: "",
						address: "",
						device_id: that.list[0].name,
					},
					header: {
						'Content-Type': 'application/json',
						'token': that.getUserInfo.data.token
					},
					method: 'POST',
					success: (res) => {
						if (res.data.code == 1) {
							that.paymentAliHandler(res.data.data)

						}

					}
				})
			},
			paymentAliHandler(paymentParams) {

				// 使用支付宝支付接口 
				uni.requestPayment({
					provider: 'alipay',
					orderInfo: paymentParams.trade_no,
					success: (res) => {
						if (res && res.resultCode === '9000') {
							that.writeBLECharacteristicValue('PBSS')
						}
					},
					fail: () => {
						// uni.hideLoading();
					},
				});
			},
			// 支付宝创建订单
			// 支付时判断蓝牙是不是连接的
			openBluetoothAdapterPay(v) {
				let that = this;
				if (v != 'open') {
					that.createorder('PCSS', 1);
					return
				}
				uni.openBluetoothAdapter({
					success: (res) => {
						// 开启支付，为了测试先注释掉
						// #ifdef MP-WEIXIN
						that.createorder('PBSS', 1);
						// #endif
						// #ifdef MP-ALIPAY
						that.createOrderAlipay()
						// #endif 
					},
					fail: (res) => {

						// that.showButton = false;
						uni.showModal({
							title: '提示',
							content: '请开启蓝牙后，重新扫码'
						});

						if (res.errCode === 10001) {}
					},
				});
			},
			// 微信创建订单
			createorder(v, numV) {

				uni.request({
					url: 'https://ys.shningmi.com/api/order/create',
					data: {
						guid: "guid",
						qty: numV,
						address: "",
						latitude: "",
						longitude: "",
						device_id: that.list[0].name
					},
					header: {
						'Content-Type': 'application/json',
						'token': that.getUserInfo.data.token
					},
					method: 'POST',
					success: (res) => {
						// that.writeBLECharacteristicValue(v)
						console.log('支付成功--------------->', res);

						uni.requestPayment({
							provider: 'wxpay', // 服务提提供商
							timeStamp: res.data.data
								.timeStamp, // 时间戳
							nonceStr: res.data.data
								.nonceStr, // 随机字符串
							package: res.data.data.package,
							signType: res.data.data
								.signType, // 签名算法
							paySign: res.data.data.sign, // 签名
							success: function(res) {
								console.log('支付成功', res);
								that.writeBLECharacteristicValue(v)
							},
							fail: function(err) {
								console.log('支付失败', err);
							}
						});


					}
				})

			},
			//写入蓝牙 这页面传入PCSS是唤醒功能
			async writeBLECharacteristicValue(v, unids) {
				console.log('这页面传入PCSS是唤醒功能', v);
				console.log('这页面传入PCSS是唤醒功能1', that.deviceId);
				console.log('这页面传入PCSS是唤醒功能2', that.serviceId);
				console.log('这页面传入PCSS是唤醒功能3', uni.getStorageSync("uuids"));

				//PASS PBSS
				let msg = v + uni.getStorageSync("uuids");
				const buffer = new ArrayBuffer(msg.length);
				const dataView = new DataView(buffer);
				for (var i = 0; i < msg.length; i++) {
					dataView.setUint8(i, msg.charAt(i).charCodeAt())
				}
				let resHex = that.ab2hex(buffer) + "0D0A";


				var buffers = new Uint8Array(resHex.match(/[\da-f]{2}/gi).map(
					function(h) {
						return parseInt(h, 16)
					})).buffer
				console.log('这页面传入PCSS是唤醒功能3buffers', buffers);
				uni.writeBLECharacteristicValue({
					deviceId: that.deviceId,
					serviceId: that.serviceId,
					characteristicId: that.characteristicId,
					value: buffers,
					success(res) {
						console.log('写入成功', res);
						that.showBtn = false
						if (v == "PBSS") {
							uni.showToast({
								icon: 'none',
								title: "开启成功"
							})
						}

						clearInterval(that.timer)
						// 开盒后清空蓝牙数据，同时断开了蓝牙
						// that.list = []
						uni.closeBLEConnection({
							deviceId: that.deviceId
						});
						uni.closeBluetoothAdapter({
							success() {},
							fail() {}
						})
						uni.stopBluetoothDevicesDiscovery({})
					},
					fail(res) {
						console.log('写入失败1', JSON.stringify(res))
					}
				})
			},
			async writeBLECharacteristicValue2(v) {
				console.log('这页面传入PCSS是唤醒功能', v);
				console.log('这页面传入PCSS是唤醒功能1', that.deviceId);
				console.log('这页面传入PCSS是唤醒功能2', that.serviceId);
				console.log('这页面传入PCSS是唤醒功能3', uni.getStorageSync("uuids"));

				//PASS PBSS
				let msg = v + uni.getStorageSync("uuids");
				const buffer = new ArrayBuffer(msg.length);
				const dataView = new DataView(buffer);
				for (var i = 0; i < msg.length; i++) {
					dataView.setUint8(i, msg.charAt(i).charCodeAt())
				}
				let resHex = that.ab2hex(buffer) + "0D0A";


				var buffers = new Uint8Array(resHex.match(/[\da-f]{2}/gi).map(
					function(h) {
						return parseInt(h, 16)
					})).buffer
				console.log('这页面传入PCSS是唤醒功能3buffers', buffers);
				uni.writeBLECharacteristicValue({
					deviceId: that.deviceId,
					serviceId: that.serviceId,
					characteristicId: that.characteristicId,
					value: buffers,
					success(res) {




					},
					fail(res) {
						console.log('写入失败1', JSON.stringify(res))
					}
				})
			},
			// ArrayBuffer转16进度字符串示例
			ab2hex(buffer) {
				const hexArr = Array.prototype.map.call(
					new Uint8Array(buffer),
					function(bit) {
						return (bit.toString(16)).slice(-2)
					}
				)
				return hexArr.join('')
			},
			// 微信开盒start

			// 微信开会end 

			// 微信授权start
			weixinAuther() {

				// #ifdef MP-WEIXIN
				wx.login({
					success(res) {
						that.getawardDetail(res.code)
					},
				});
				// #endif
				// #ifdef MP-ALIPAY
				that.userAlipayLoginCode()
				// #endif
			},
			// 支付宝登录授权认证
			userAlipayLoginCode() {
				my.getAuthCode({
					scopes: 'auth_user',
					success: res => {
						that.alipayLogin(res.authCode)
					},
				});
			},
			alipayLogin(code) {
				uni.request({
					url: 'https://ys.shningmi.com/api/alipay/login',
					data: {
						code
					},
					header: {
						'Content-Type': 'application/json',

					},
					method: 'POST',
					success: (res) => {

						let {
							data
						} = res;
						if (data.code == 1) {
							console.log('===支付宝====', res)
							that.getUserInfo = data;
							that.initBLEAdP();
						}



					}
				})
			},
			async getawardDetail(code) {

				await uni.request({
					url: 'https://ys.shningmi.com/api/login/login',
					data: {
						code

					},
					header: {
						'Content-Type': 'application/json'
					},
					method: 'POST',
					success: (res) => {
						let {
							data
						} = res;
						that.getUserInfo = data;
						that.initBLEAdP();

					}
				})

			},

			// 微信授权end
		}
	}
</script>

<style lang="scss" scoped>
	.langya0 {
		min-height: 100vh;
		background-color: #4E85FD;
		padding-top: 300rpx;

		.langya5 {
			color: #fff;
			text-align: center;
			margin: 40rpx 0;
			font-size: 18px;
		}

		.langya1 {
			width: 200rpx;
			height: 200rpx;
			margin: 0 auto;


		}

		.langya1 image {
			width: 100%;
			height: 100%;
		}

		.langya2 {

			display: flex;
			flex-direction: row;
			align-items: center;
			justify-content: space-around;
			margin: 0 auto;
			margin-top: 60rpx;

			.langya3 {
				background-color: #fff;
				padding: 10px;
				font-size: 25px;
				border-radius: 10rpx;
				margin-right: 10rpx;
				color: #4E85FD;

			}

			.langya4 {
				background-color: #fff;
				padding: 10px;
				font-size: 25px;
				border-radius: 10rpx;
				margin-left: 10rpx;
				color: #4E85FD;
			}
		}
	}
</style>